package com.zuqiuzhandui.liveing.net;

import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.widget.Toast;

import com.code19.library.GsonUtil;
import com.code19.library.L;
import com.zuqiuzhandui.liveing.base.BaseActivity;
import com.zuqiuzhandui.liveing.myInterfacce.Constant;
import com.zuqiuzhandui.liveing.view.login.LoginActivity;

import java.lang.ref.WeakReference;

import rx.Subscriber;

/**
 * Created by yq on 2016-10-10.
 */

public class ProgressSubscriber<T> extends Subscriber<T> implements ProgressCancelListener{
    private SubscriberOnNextListener mSubscriberOnNextListener;
    private WeakReference<Context> mContext;
    private ProgressDialogHandler mProgressDialogHandler;

    public ProgressSubscriber(SubscriberOnNextListener mSubscriberOnNextListener,Context context){
        this.mSubscriberOnNextListener=mSubscriberOnNextListener;
        this.mContext=new WeakReference(context);
        mProgressDialogHandler=new ProgressDialogHandler(context,this,true);
    }

    @Override
    public void onCompleted() {
        dismissProgressDialog();
//        Toast.makeText(mContext.get(), "Get Top Movie Completed", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onError(Throwable e) {
        dismissProgressDialog();
        if (Looper.myLooper()==Looper.getMainLooper())
        {
            L.d("当前线程是主线程");
        }
        if (mSubscriberOnNextListener==null) {
            L.d("mSubscriberOnNextListener is null");
        }
        if (e.getMessage().equals(Constant.TOKEN_ERROR)){
            Intent intent=new Intent(mContext.get(), LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.get().startActivity(intent);
        }
        L.d( e.getMessage());
        Toast.makeText(mContext.get(),e.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onNext(T t) {
            mSubscriberOnNextListener.onNext(t);
    }

    @Override
    public void onStart() {
        showProgressDialog();
    }

    @Override
    public void onCancelProgress() {
        if (!this.isUnsubscribed())
        {
            this.unsubscribe();
        }
    }

    private void showProgressDialog()
    {
        if (mProgressDialogHandler!=null) {
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.SHOW_PROGRESS_DIALOG).sendToTarget();
        }
    }

    private void dismissProgressDialog()
    {
        if (mProgressDialogHandler!=null) {
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.DISMISS_PROGRESS_DIALOG).sendToTarget();
            mProgressDialogHandler=null;
        }
    }

}
